import React, {Component, PropTypes} from 'react'
import {Card, Tag, Button, Modal, Form, Input, message, Popconfirm, Col, Radio, Tabs, DatePicker, Tooltip} from 'antd'
import CheckRecord from '../../../../common/components/users/CheckRecord'
import Styles from './Index.less'
import {fetchPost} from '../../../../../utils/request'
import Identity from '../../../../common/components/users/Identity'
import Photos from '../../../../common/components/users/Photos'
import Risk from '../../../common/detail/risk/Risk'
import BorrowRecord from '../../../../common/components/users/BorrowRecord'
import PhoneRemarkRecord from '../../../../common/components/users/PhoneRemarkRecord'
import KycAuthResult from '../../../common/detail/kyc/KycAuthResult'
import TradeBankInfo from '../../../../common/components/users/TradeBankInfo'
import AppLists from '../../../../common/components/users/AppLists'
import Contacts from './info/Contacts'
import BasicInfo from "../../../../common/components/users/BasicInfo";
import Profession from "../../../../common/components/users/Profession";
import Contact from "../../../../common/components/users/Contact";
import Info from "../../../common/detail/info/Info";
import Relation from "../../../../common/components/users/Relation";

const FormItem = Form.Item
const CheckableTag = Tag.CheckableTag
const TabPane = Tabs.TabPane
const RadioGroup = Radio.Group

class UncontrolledCheckableTag extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      activity: props.activity,
    }
  }

  componentWillReceiveProps(props) {
    if (props.activity != this.state.activity) {
      this.setState({
        activity: props.activity,
      })
    }
  }

  handleChange(activity) {
    this.setState({
      activity: !this.state.activity,
    })
    this.props.chooseTag(activity)
  };

  render() {
    return <CheckableTag checked={this.state.activity}
                         onChange={this.handleChange.bind(this)}>
      {this.props.tagName}
    </CheckableTag>
  }
}

class Detail extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      id: props.id,
      userId: props.userId,
      tradeNo: props.tradeNo,
      activeKey: props.activeKey,
      processNode: props.processNode,
      item: props.item,
      showDetail: true,
      stepType: props.stepType,
      visible: false,
      tagData: [],
      tagIDs: {},
      riskResult: '',
      managerInfo: {
        finish: '',
        remain: '',
      },
      photoType: '',
      currentType: '',
      reuploadTypeList: null,
      extraStatus: props.extraStatus,
      photoReUploadTime: props.photoReUploadTime,
      photoReUploadAllow: props.photoReUploadAllow,
      canReedit: false,
      questions: [],
      jobLevelTag: null,
      jobLevelTagData: [{"key": "WORKLEVEL", "answer": "Level 1"}, {
        "key": "WORKLEVEL",
        "answer": "Level 2"
      }, {"key": "WORKLEVEL", "answer": "Level 3"}, {
        "key": "WORKLEVEL",
        "answer": "Level 4"
      }, {"key": "WORKLEVEL", "answer": "Sensitive occupation"}, {"key": "WORKLEVEL", "answer": "Others"}],
    }
  }

  componentDidMount() {
    this.getData()
  }

  getData() {
    let self = this
    if (this.state.userId != null) {
      function getTags() {
        return new Promise((resolve, reject) => {
          fetchPost(`/audit/usertag/${self.state.userId}/1/query`).then((res) => {
            if (res.code === 0) {
              if (res.data.list != null) {
                resolve(res)
              } else {
                reject('')
              }
            } else {
              message.error(res.msg)
              reject(res)
            }
          })
        })
      }

      // function getManagerInfo() {
      //   return new Promise((resolve, reject) => {
      //     fetchPost(`/audit/usertag/${self.state.userId}/query`).then((res) => {
      //       if(res.code === 0) {
      //         resolve(res)
      //       } else {
      //         message.error(res.msg)
      //         reject(res)
      //       }
      //     })
      //   })
      // }

      Promise.all([getTags()]).then((res) => {
        let [resTags, resManagerInfo] = [res[0], res[1]]
        resTags.data.list.forEach((value, index) => {
          value.childList.forEach((val, ind) => {
            if (val.activity) {
              this.state.tagIDs[val.tagId] = true
            }
          })
        })

        self.setState({
          tagData: resTags.data.list || [],
          managerInfo: {
            remain: '',
            finish: ''
          }
        }, () => {
          fetchPost(`/audit/usertag/${self.state.userId}/phone/query`, {}).then((res1) => {
            if (res1.code === 0) {
              res1.data.list.forEach((value1, index1) => {
                value1.childList.forEach((val1, ind1) => {
                  if (val1.activity) {
                    this.state.tagIDs[val1.tagId] = true
                  }
                })
              })

              let tmp = [];
              tmp = self.state.tagData;
              res1.data.list.map(tt => {
                tmp.push(tt);
              });

              self.setState({
                tagData: tmp || [],
                managerInfo: {
                  remain: '',
                  finish: '',
                },
              })
            } else {
              message.error(res.msg)
            }
          })
        })
      })

      fetchPost(`/risk/result/get`, {
        tradeNo: this.state.tradeNo
      }).then(json => {
        if (json.code === 0) {
          if (json.data != null) {
            this.setState({
              riskResult: json.data.riskResult,
            })
          }
        } else {
          this.setState({
            riskResult: '',
          })
        }
      })
    }
  }

  componentWillReceiveProps(props) {
    if (this.state.id != props.id || this.state.userId != props.userId) {
      this.setState({
        id: props.id,
        activeKey: props.activeKey,
        userId: props.userId,
        tradeNo: props.tradeNo,
        stepType: props.stepType,
        item: props.item,
        extraStatus: props.extraStatus,
        photoReUploadTime: props.photoReUploadTime,
        photoReUploadAllow: props.photoReUploadAllow,
        mobileRedialAllow: props.mobileRedialAllow,
        questions: [],
        jobLevelTag: null,
      }, () => {
        this.getData()
      })
    }
  }

  onChange(activeKey) {
    this.setState({activeKey})
  }

  changeOrder(type, id) {
    this.props.changeOrder(type, id)
  }

  operation(type) {
    this.setState({
      currentType: type
    }, () => {
      let reason = this.props.form.getFieldValue('checkReason')
      let self = this
      let tagIdList = []
      if (this.state.currentType == 'refuse' && !reason) {
        message.info("Please enter the reason");
        return false;
      }
      if (type == 'pass') {
        if (this.state.questions == null || this.state.questions.length == 0) {
          message.warning('Please choose the question tag')
          return false
        }
      }
      for (let i in this.state.tagIDs) {
        tagIdList.push(i)
      }

      this.props.form.validateFields((errors, values) => {
        if (!errors) {
          let operationParams = {
            auditNo: this.state.id,
            message: reason,
            userCode: this.state.userId,
            tradeNo: this.state.tradeNo,
            processNode: this.state.processNode,
            tagIdList,
            photoType: this.state.photoType
          }

          switch (type) {
            case 'pass':
              fetchPost(`/audit/question/${this.state.tradeNo}/initialOrderNew/answer`, {
                questions: this.state.questions,
                worksheetType: 'levelTag',
                tradeNo: this.state.tradeNo
              }).then(res => {
                //不论成功失败都调用pass接口
              })

              fetchPost('/audit/operate/pass', operationParams).then((json) => {
                if (json.code === 0) {
                  self.clearReason()
                  this.state.tagIDs = {}
                  self.changeOrder('pass', self.state.id)
                  message.success('Operation Success')
                } else {
                  message.error(json.msg)
                }
              })
              break

            case 'wait':
              fetchPost('/audit/operate/staging', operationParams).then((json) => {
                if (json.code === 0) {
                  self.clearReason()
                  self.changeOrder('wait', self.state.id)
                  this.state.tagIDs = {}
                  message.success('Operation Success')
                } else {
                  message.error(json.msg)
                }
              })
              break

            case 'refuse':
              fetchPost('/audit/operate/refuse', operationParams).then((json) => {
                if (json.code === 0) {
                  self.clearReason()
                  self.changeOrder('refuse', self.state.id)
                  this.state.tagIDs = {}
                  message.success('Operation Success')
                } else {
                  message.error(json.msg)
                }
              })
              break

            case 'reedit':
              fetchPost('/audit/operate/reedit', operationParams).then((json) => {
                if (json.code === 0) {
                  self.clearReason()
                  self.changeOrder('refuse', self.state.id)
                  this.state.tagIDs = {}
                  message.success('Operation Success')
                } else {
                  message.error(json.msg)
                }
              })
              break
            default:
          }
        }
      })
    })
  }

  // 独立按钮使用
  operationV2(type) {
    this.setState({
      currentType: type
    }, () => {
      let reason = ''
      let self = this
      if (this.state.currentType == 'refuse') {
        reason = 'Photo audits exceed the number limit'
      }
      let operationParams = {
        auditNo: this.state.id,
        message: reason,
        userCode: this.state.userId,
        tradeNo: this.state.tradeNo,
        processNode: this.state.processNode,
        tagIdList: [],
        photoType: this.state.photoType
      }

      switch (type) {
        case 'pass':
          fetchPost('/audit/operate/pass', operationParams).then((json) => {
            if (json.code === 0) {
              self.clearReason()
              this.state.tagIDs = {}
              self.changeOrder('pass', self.state.id)
              message.success('Operation Success')
            } else {
              message.error(json.msg)
            }
          })
          break

        case 'refuse':
          fetchPost('/audit/operate/refuse', operationParams).then((json) => {
            if (json.code === 0) {
              self.clearReason()
              self.changeOrder('refuse', self.state.id)
              this.state.tagIDs = {}
              message.success('Operation Success')
            } else {
              message.error(json.msg)
            }
          })
          break

        case 'reedit':
          fetchPost('/audit/operate/reedit', operationParams).then((json) => {
            if (json.code === 0) {
              self.clearReason()
              self.changeOrder('refuse', self.state.id)
              this.state.tagIDs = {}
              message.success('Operation Success')
            } else {
              message.error(json.msg)
            }
          })
          break
        default:
      }
    })
  }

  clearReason() {
    this.props.form.setFieldsValue({
      checkReason: '',
    })
    this.setState({
      visible: false,
      tagIDs: {},
    }, () => {
      this.getData()
    })
  }

  extraContent() {
    return (
      <div>
      <span>
        <span className='ml10'> Loan ID: <span
          className='color-main'>{this.state.item.tradeNo || ''}</span></span>
        <span className='ml10'> Amount/Tenure:
          <span className='color-main'>
            {`${this.state.item.realCapital ||
            ''}₹/${this.state.item.productDuration || ''}`}
          </span>
        </span>
        <span className='ml10 mr10'>System Result:
          <span className='color-main'>{this.state.riskResult}</span>
        </span>
        {
          this.state.stepType != 'photoCheckReupload'
          && this.state.stepType != 'riskWaiting'
          && this.state.userId ?
            <Button type='primary'
                    onClick={this.changeModal.bind(
                      this)}>Operate</Button>
            : null
        }
      </span>
      </div>
    )
  }

  chooseTag(activity, id, name) {
    let self = this
    let form = this.props.form
    this.state.tagData.forEach((value, index) => {
      value.childList.forEach((val, ind) => {
        if (val.tagId == id) {
          val.activity = activity
        }
      })
    })

    this.setState({
      tagData: this.state.tagData || [],
    })

    if (activity) {
      this.state.tagIDs[id] = true
      if (form.getFieldValue('checkReason')) {
        form.setFieldsValue({
          checkReason: `${form.getFieldValue('checkReason') + name};`,
        })
      } else {
        form.setFieldsValue({
          checkReason: `${name};`,
        })
      }
    } else {
      let beforeReason = self.props.form.getFieldValue('checkReason')
      let currentReason = beforeReason.replace(new RegExp(`${name};`, 'g'), '')
      form.setFieldsValue({
        checkReason: currentReason,
      })
      delete this.state.tagIDs[id]
    }
  }

  changeParams(data) {
    if (data.photoType) {
      this.setState({
        photoType: data.photoType
      })
    }
  }

  photoReuploadCallback = (reuploadTypeList) => {
    this.setState({
      reuploadTypeList: reuploadTypeList,
    })
  };

  reuploadPhoto = () => {
    let self = this;
    if (this.state.reuploadTypeList != null) {
      fetchPost(`/user/photo/reupload`, {
        photoTypeList: this.state.reuploadTypeList,
        tradeNo: this.state.tradeNo,
      }).then(json => {
        if (json.code === 0) {
          self.clearReason();
          self.changeOrder('reupload', self.state.id);
          message.info('success')
        } else {
          message.error(json.msg)
        }
      })
    }
  }

  changeModal() {
    this.setState({
      visible: !this.state.visible
    })
  }

  showReeditButton() {
    if (this.state.canReedit) {
      return <Popconfirm placement='top' title='Are you sure?'
                         onConfirm={() => {
                           this.operation('reedit')
                         }}>
        <Button type='default' className='ml10'>Reject-re-edit</Button>
      </Popconfirm>
    } else {
      return <Popconfirm placement='top' title='Are you sure?'
                         onConfirm={() => {
                           this.operation('reedit')
                         }}>
        <Button type='default' disabled className='ml10'>Reject-re-edit</Button>
      </Popconfirm>
    }
  }

  tabChangeCallback = (key) => {
    console.log(key, 'choose tab call back')
  }

  chooseJobLevelTag(value) {
    let questions = [{key: value.key, answer: value.answer}];
    this.setState({
      jobLevelTag: value.answer,
      questions: questions
    })
  }

  getJobLevelColor(jobLevelTag) {
    if (this.state.jobLevelTag == jobLevelTag) {
      return '#87d068'
    }
  }

  render() {
    const {getFieldDecorator} = this.props.form;
    return (
      <div>
        <Modal visible={this.state.visible}
               onOk={this.clearReason.bind(this)}
               onCancel={this.clearReason.bind(this)}
               footer={null}
               width="650"
        >
          <Form>
            <FormItem className={Styles.operationHeader}>
              <span className={Styles.title}>Order operation</span>
              <Popconfirm placement='top' title='Confirm pass?'
                          onConfirm={() => {
                            this.operation('pass')
                          }}>
                {(this.props.extraStatus != null && typeof (this.props.extraStatus) != 'undefined' && this.props.extraStatus == 1) ?
                  <Button type='primary' className='ml20' disabled>Pass</Button>
                  : (this.props.extraStatus != null && typeof (this.props.extraStatus) != 'undefined' && this.props.extraStatus == 9) ?
                    <Button type='primary' className='ml20'>Pass</Button>
                    : (this.state.reuploadTypeList == null ?
                      <Button type='primary' className='ml20'>Pass</Button>
                      : <Button type='primary' className='ml20' disabled>Pass</Button>)}
              </Popconfirm>

              <Popconfirm placement='top' title='Confirm re-upload?'
                          onConfirm={this.reuploadPhoto}>
                {this.state.stepType == 'photoCheckReupload' ?
                  <Button type='primary' className='ml20'>Re-upload</Button>
                  :
                  (this.state.reuploadTypeList == null || (this.state.photoReUploadAllow != 1) ?
                    <Button type='primary' className='ml20' disabled>Re-upload</Button>
                    : <Button type='primary' className='ml20'>Re-upload</Button>)}
              </Popconfirm>

              <Popconfirm placement='top' title='Confirm refuse?'
                          onConfirm={() => {
                            this.operation('refuse')
                          }}>
                <Button type='primary' className='ml10'>Refuse</Button>
              </Popconfirm>
              <Popconfirm placement='top' title='Four hours later?'
                          onConfirm={() => {
                            this.operation('wait')
                          }}>
                {this.state.mobileRedialAllow != 1 ?
                  <Button type='default' className='ml10' disabled style={{width: '90px'}}>Postpone</Button> :
                  <Button type='default' className='ml10' style={{width: '90px'}}>Postpone</Button>}
              </Popconfirm>
              {/*{this.showReeditButton()}*/}
            </FormItem>

            <FormItem>
              {getFieldDecorator('checkReason',
                {rules: [{message: 'Please enter the reason'}]})(
                <Input placeholder='Please enter the reason' className='mh150' type='textarea'/>,
              )}
            </FormItem>

            <FormItem>
              <div><strong>What is his/her job level?</strong></div>
              <div>
                {
                  this.state.jobLevelTagData.map((value, index) => (
                    <Tag key={index} onClick={(e) => this.chooseJobLevelTag(value)}
                         color={this.getJobLevelColor(value.answer)}>{value.answer}</Tag>
                  ))
                }
              </div>
              <div className={Styles.problemDesc}>
                <ul className={Styles.ulSty}>
                  <li className={Styles.liSty}>Level 1: supervisor, manager, hr, finance, owner, partner
                  </li>
                  <li className={Styles.liSty}>Level 2: worker, service, maintenance
                  </li>
                  <li className={Styles.liSty}>Level 3: driver, Courier
                  </li>
                  <li className={Styles.liSty}>Level 4: cleaning, handyman
                  </li>
                  <li className={Styles.liSty}>Sensitive occupation: police officers, lawyers, soldiers
                  </li>
                </ul>
              </div>
            </FormItem>
          </Form>

          <Tabs onChange={this.tabChangeCallback} type="card">
            <TabPane tab="Reason label" key="1">
              <Card noHovering>
                {
                  this.state.tagData.map((cate, index) => {
                    if (cate.type !== 13 && cate.type !== 14 && cate.type !== 15 && cate.type !== 16) {
                      return <div key={index}>

                        <span className='font13 color-main'>{cate.typeName}</span>:
                        <br/>
                        {
                          cate.childList.map((tag, index) => (
                            <UncontrolledCheckableTag
                              key={index}
                              chooseTag={(activity) => this.chooseTag(activity,
                                tag.tagId, tag.name)} tagName={tag.name}
                              activity={tag.activity}/>
                          ))
                        }
                      </div>
                    }
                  })
                }
              </Card>
            </TabPane>
            <TabPane tab="Re-edit label" key="2">
              <Card noHovering>
                {
                  this.state.tagData.map((cate, index) => {
                    if (cate.type === 14 || cate.type === 15 || cate.type === 16) {
                      return <div key={index}>

                        <span className='font13 color-main'>{cate.typeName}</span>:
                        <br/>
                        {
                          cate.childList.map((tag, index) => (
                            <UncontrolledCheckableTag
                              key={index}
                              chooseTag={(activity) => this.chooseTag(activity,
                                tag.tagId, tag.name)} tagName={tag.name}
                              activity={tag.activity}/>
                          ))
                        }
                      </div>
                    }
                  })
                }
              </Card>
            </TabPane>
          </Tabs>
        </Modal>


        <div className={Styles.photoDetailWrap}>
          <div className='mb10'>{this.extraContent()}</div>

          <Card bodyStyle={{padding: 0}} bordered={false} noHovering={true}>
            <Tabs className={Styles.tabs} activeKey={this.state.activeKey}
                  onChange={(e) => this.onChange(e)}>
              <TabPane tab='Photo Information' key='detail'>
                {
                  this.state.activeKey === 'detail' ?
                    <div>
                      {/*Information*/}
                      <Col span={24}>
                        <Identity userId={this.state.userId} tradeNo={this.state.tradeNo}/>
                        {/*<OCR userId={this.state.userId} tradeNo={this.state.tradeNo} stepType={this.state.stepType}/>*/}
                      </Col>
                      {/*Kyc+Selfie+PanCard*/}
                      <Col span={24}>
                        <Photos changeParams={(data) => {
                          this.changeParams(data)
                        }} userId={this.state.userId} tradeNo={this.state.tradeNo}
                                photoReUploadTime={this.state.photoReUploadTime}
                                photoReUploadAllow={this.state.photoReUploadAllow}
                                callbackParent={this.photoReuploadCallback}
                                stepType={this.state.stepType}
                        />
                      </Col>
                    </div>
                    : <span/>
                }
              </TabPane>
              <TabPane tab='Basic Information' key='info'>
                <Col span={24}>
                  <Tabs onChange={this.callback} type="line">
                    <TabPane tab="BASIC" key="1">
                      <BasicInfo userId={this.state.userId} tradeNo={this.state.tradeNo}
                                 stepType={this.state.stepType}/>
                    </TabPane>
                    <TabPane tab="WORKING" key="2">
                      <Profession orderId={this.state.id} userId={this.state.tradeNo}/>
                    </TabPane>
                    {
                      this.state.processNode == '1' ? null
                        :
                        <TabPane tab="CONTACT" key="3">
                          <Contact id={this.state.id} userId={this.state.tradeNo}/>
                        </TabPane>
                    }
                  </Tabs>
                </Col>
                {/*Bank Info*/}
                <Col span={24}>
                  <TradeBankInfo userId={this.state.userId} tradeNo={this.state.tradeNo}/>
                </Col>
                {
                  this.state.activeKey === 'info'
                    ? <div className={Styles.tabsWrapper}>
                      <Col span={12}>
                        <Risk processNode={this.state.processNode} id={this.state.item} userId={this.state.tradeNo}/>
                        {/*<FacePhoto userId={this.state.userId} tradeNo={this.state.item.tradeNo}
                         stepType={this.state.stepType}/>*/}
                        {/*<OCR userId={this.state.userId} tradeNo={this.state.item.tradeNo}
                         stepType={this.state.stepType}/>*/}
                        <KycAuthResult userId={this.state.userId} tradeNo={this.state.item.tradeNo}
                                       stepType={this.state.stepType}/>
                      </Col>
                      <Col span={12}>
                        <Card title='' bodyStyle={{padding: '5px'}} noHovering>
                          <Contacts userId={this.state.tradeNo} id={this.state.id} showCategory={['2', '3']}/>
                          <AppLists userId={this.state.tradeNo}/>
                          {/*关于userId和tradeNo，写乱了，坑*/}
                        </Card>
                      </Col>
                    </div>
                    : <span></span>
                }
              </TabPane>

              <TabPane tab='Contact' key='contactRecord'>
                {
                  this.state.activeKey === 'contactRecord' ?
                    <div className={Styles.tabsWrapper}>
                      <Contacts userId={this.state.tradeNo} id={this.state.id}/>
                    </div>
                    : <span/>
                }
              </TabPane>

              <TabPane tab='Application History' key='records'>
                {
                  this.state.activeKey === 'records'
                    ? <div className={Styles.tabsWrapper}>
                      <BorrowRecord userId={this.state.tradeNo}/>
                      {/*<PhoneRemarkRecord userId={this.state.tradeNo}/>*/}
                      <CheckRecord userId={this.state.userId} tradeNo={this.state.tradeNo}/>
                    </div>
                    : <span/>
                }
              </TabPane>
            </Tabs>

            <Col span={24}>
              {
                this.state.activeKey === 'records' ? <span></span> :
                  <CheckRecord userId={this.state.userId} tradeNo={this.state.tradeNo}/>
              }
            </Col>
          </Card>

        </div>
      </div>
    )
  }
}

Detail = Form.create()(Detail)

export default Detail
